<template>
  <div>
    <BasicTable @register="registerTable" size="small" @fetch-success="onFetchSuccess">
      <!-- 标记 -->
      <template #statusFlag="{ record }">
        <template v-if="record.flag == 0">
          <Tag :color="'green'">启用</Tag>
        </template>
        <template v-if="record.flag == 5">
          <Tag :color="'yellow'">禁用</Tag>
        </template>
        <template v-if="record.flag == 9">
          <Tag :color="'red'">已删除</Tag>
        </template>
      </template>

      <!-- 部门名称设置缩进对齐；子级部门缩进1rem -->
      <template #name="{ record }">
        <template v-if="record.level == 1">
          <span>{{ record.name }}</span>
        </template>
        <template v-else-if="record.level == 2">
          <span style="display: block; text-indent: 1em">{{ record.name }}</span>
        </template>
        <template v-else-if="record.level == 3">
          <span style="display: block; text-indent: 2em">{{ record.name }}</span>
        </template>
      </template>

      <template #toolbar>
        <a-button type="primary" @click="onAddDept"> 新增 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditDept.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteDept.bind(null, record),
              },
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '设置部门人员',
              color: 'success',
              onClick: onSetUsers.bind(null, record),
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '设置部门负责人',
              color: 'success',
              onClick: onSetLeaders.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <addOrUpdateDept @register="registerAddOrUpdateForm" @success="afterSuccess" />
    <userTreeModel @register="registerUserTree" @success="afterSuccess" />
    <leaderTreeModal @register="registerLeaderTree" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, provide, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { queryTreeTable, deleteDept } from '/@/api/project/dept';
  import { deptTableColumns } from './dept.data';

  import { useUserStore } from '/@/store/modules/user';

  import { Tag } from 'ant-design-vue';

  //引入子组件
  import addOrUpdateDept from './AddOrUpdateDept.vue';
  import userTreeModel from './DeptUserTreeModel.vue';
  import leaderTreeModal from './DeptLeaderUserTreeModel.vue';
  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage } = useMessage();

  const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();
  const [registerUserTree, { openModal: openUserTree }] = useModal();
  const [registerLeaderTree, { openModal: openLeaderTree }] = useModal();

  export default defineComponent({
    name: 'DeptManagement',
    components: { BasicTable, TableAction, Tag, addOrUpdateDept, userTreeModel, leaderTreeModal },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('部门管理');
      provide('moduleName', moduleName);

      // //获取当前登录用户的项目编码
      const userStore = useUserStore();
      let currentProjectCode = userStore.getUserCurrentProjectCode;

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable, { reload, expandAll }] = useTable({
        title: '部门管理',
        api: queryTreeTable,
        searchInfo: { pcode: currentProjectCode }, //额外的请求参数
        columns: deptTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: false,
        bordered: true,
        canResize: true,
        striped: false,
        isTreeTable: true,
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 接口请求成功后触发：展开所有列表项
       */
      function onFetchSuccess() {
        nextTick(expandAll);
      }

      /**
       * 打开新增窗口
       */
      function onAddDept() {
        //使用props传递数据至子组件，在data参数中指定
        openAddOrUpdateForm(true, { op: OperationTypeEnum.ADD });
      }

      /**
       * 打开编辑窗口
       */
      function onEditDept(record: Recordable) {
        openAddOrUpdateForm(true, { op: OperationTypeEnum.EDIT, dataId: record.id });
      }

      /**
       * 打开设置部门关联用户窗口
       */
      function onSetUsers(record: Recordable) {
        openUserTree(true, { op: '设置部门关联用户', dataId: record.id });
      }

      function onSetLeaders(record: Recordable) {
        openLeaderTree(true, { op: '设置部门负责人', dataId: record.id });
      }

      /**
       * 删除
       */
      function onDeleteDept(record: Recordable) {
        deleteDept(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      return {
        moduleName,
        registerTable,
        afterSuccess,
        registerAddOrUpdateForm,
        onAddDept,
        onEditDept,
        onDeleteDept,
        onFetchSuccess,
        registerUserTree,
        onSetUsers,
        onSetLeaders,
        registerLeaderTree,
      };
    },
  });
</script>
